<template>
	<el-input v-model="areaDetail" placeholder="区域地址">
		<template #prepend>
			<el-cascader
				v-model="selectedOptions"
				:options="areaOptions"
				:props="cascaderProps"
				style="width: 153px"
				:placeholder="placeholder"
				:disabled="disabled"
				:clearable="clearable"
				@change="handleChange"
			/>
		</template>
	</el-input>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { defineProps, defineEmits } from 'vue'
import {
	provinceAndCityData,
	CodeToText,
	TextToCode,
} from 'element-china-area-data'
//将regionData数据绑定到级联选择器上即可

const areaDetail = ref('')
// 组件属性
const props = defineProps<{
	// 绑定值：[省份编码, 城市编码]
	modelValue?: string
	// 占位文本
	placeholder?: string
	// 是否禁用
	disabled?: boolean
	// 是否可清除
	clearable?: boolean
}>()

// 组件事件
const emit = defineEmits<{
	// 更新绑定值
	(e: 'update:modelValue', value: string[] | null): void
	// 选择变化事件
	(
		e: 'change',
		value: {
			provinceCode: string
			provinceName: string
			cityCode: string
			cityName: string
		}
	): void
}>()

// 级联选择器配置
const cascaderProps = {
	value: 'value',
	label: 'label',
	children: 'children',
	expandTrigger: 'click', // 点击展开子列表
}

// 选中的值
const selectedOptions = computed(() => {
	// const areaObj = splitAddress(props.modelValue)
	console.log(
		'地区列表'
		// TextToCode(areaObj.province)
		// TextToCode(areaObj.city)
	)

	return props.modelValue || []
})

// 处理后的省市数据
const areaOptions = ref(provinceAndCityData)

// 监听外部传入的modelValue变化
watch(
	() => props.modelValue,
	(newVal) => {
		if (newVal) {
			selectedOptions.value = newVal
		} else {
			selectedOptions.value = []
		}
	},
	{ immediate: true }
)

// 处理选择变化
const handleChange = (value: string[] | null) => {
	// 触发v-model更新
	emit('update:modelValue', value)

	if (value && value.length === 2) {
		const provinceIndex = areaOptions.value.findIndex(
			(province) => province.value === value[0]
		)
		const cityIndex = areaOptions.value[provinceIndex].children.findIndex(
			(city) => city.value === value[1]
		)

		const provinceName = areaOptions.value[provinceIndex].label
		const cityName = areaOptions.value[provinceIndex].children[cityIndex].label

		// 触发change事件，返回详细信息
		emit('change', {
			provinceCode: value[0],
			provinceName,
			cityCode: value[1],
			cityName,
		})
	}
}

function splitAddress(str: string) {
	const regex = /^(.+?省|.+?市)(.+?市|.+?区|.+?县)(.+?区|.+?县)(.*)$/
	const m = str.match(regex)
	if (!m) return null
	// 直辖市会匹配出 省=北京市 市=北京市 县=朝阳区，可按需再处理
	return {
		province: m[1], // 安徽省
		city: m[2], // 安庆市
		district: m[3], // 望江县
		detail: m[4], // 其余
	}
}
</script>
<style lang="less" scoped>
.customAreaSelect {
	display: flex;
}
:deep(.el-input-group__prepend) {
	padding: 0;
}
</style>
